﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ConsolidationTool.WebParts.ControlTemplates;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Web;
using ConsolidationTool.Common;

namespace ConsolidationTool.WebParts.Layouts.CReport
{
    public partial class koDillReport : FSReportBase
    {
        public string ListTitle;
        public List<fsentity> Relationships = new List<fsentity>();
        public List<ListIns> TableData = new List<ListIns>();

        public override CommonEntitySelector TopSelector
        {
            get
            {
                return commonEntitySelector as ControlTemplates.CommonEntitySelector;
            }
        }
        public override void BeforLoad()
        {
            base.BeforLoad();

            title.Text = ListTitle = HttpUtility.UrlDecode(Request["t"]); ;

            if (!IsPostBack&&!Automatic)
                loadConfigYearMonth();

            InitBaseInfo();
        }


        string GetFieldTemplate()
        {
            string temp = string.Empty;
            //using (StreamReader sr = new StreamReader(Server.MapPath("FieldTemplate.js")))
            //{
            //    temp = sr.ReadToEnd();
            //}
            return temp;
        }

        void InitBaseInfo()
        {

            Title_HRM1.Text = TopSelector.yearTextBox.Text + ".01";
            Title_HRM2.Text = TopSelector.yearTextBox.Text + ".02";
            Title_HRM3.Text = TopSelector.yearTextBox.Text + ".03";
            Title_HRM4.Text = TopSelector.yearTextBox.Text + ".04";
            Title_HRM5.Text = TopSelector.yearTextBox.Text + ".05";
            Title_HRM6.Text = TopSelector.yearTextBox.Text + ".06";
            Title_HRM7.Text = TopSelector.yearTextBox.Text + ".07";
            Title_HRM8.Text = TopSelector.yearTextBox.Text + ".08";
            Title_HRM9.Text = TopSelector.yearTextBox.Text + ".09";
            Title_HRM10.Text = TopSelector.yearTextBox.Text + ".10";
            Title_HRM11.Text = TopSelector.yearTextBox.Text + ".11";
            Title_HRM12.Text = TopSelector.yearTextBox.Text + ".12";
        }

        private void loadConfigYearMonth()
        {
            // lbCompanyName.Text = Constants.Company_Name;
            TopSelector.yearTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Year);
            TopSelector.monthTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Month);
        }

        public override void GenerateReport_Click(object sender, EventArgs e)
        {
            //邦定current月数据
            int m = Convert.ToInt32(TopSelector.monthTextBox.Text);

            for (int i = 1; i <= m; i++)
            {
                BindLastMonth(TopSelector.drpEntity.SelectedValue, TopSelector.yearTextBox.Text, i.ToString());
            }
            reportData.DataSource = TableData;//.OrderBy(p => p.AccountCode);
            reportData.DataBind();
        }

        public void BindLastMonth(string coCd, string year, string month)
        {
            string y = year;
            string m = (Convert.ToInt32(month)).ToString();
            SPListItem it = Common.BusinessService.GetItem(coCd, y, m, ListTitle);

            if (it != null)
            {
                string currency = it["Currency"] + "";
                string BillData = it["BillData"] + "";

                Relationships = new JavaScriptSerializer().Deserialize<List<fsentity>>(BillData);
              //  int currentIndex = 0;
                Relationships.Where(p => !p.controlrow).ToList().ForEach(p =>
                {

                    if (p.emptyrow)
                    {
                        if (month == "1")
                        {
                            var empty = new ListIns();
                            if (!string.IsNullOrEmpty(p.description))
                            {
                                empty.AccountCode = p.description;
                            }

                            TableData.Add(empty);
                        }
                    }
                    else
                    { 
                        var instance = CreateKoInstance(month, currency, p, false, 0);
                        if (p.subrow != null)
                        {
                            // var parentNode = TableData.FirstOrDefault(c => c.AccountCode == instance.AccountCode);
                            int index = TableData.IndexOf(instance) + 1;
                            p.subrow.ForEach(a =>
                            {
                                CreateKoInstance(month, currency, a, true, index);
                            });
                        }
                    }
                   // currentIndex++;
                });
            }

        }

        private ListIns CreateKoInstance(string month, string currency, BaseKoEntity p, bool insert, int index)
        {
            bool fieldExist = true;

            var subRowInstance = new fssubentity() ;

            var ins = TableData.FirstOrDefault(a => a.AccountCode == p.accountcode);

            if (ins == null)
            {
                fieldExist = false;
                ins = new ListIns();
                ins.AccountCode = p.accountcode;
                ins.Description = p.description;
                ins.Unit = p.unit;
                ins.Type = "";
            }
            if (p is fssubentity)
            {
                subRowInstance = p as fssubentity;

                ins.Description = subRowInstance.entity.IsNullOrEmpty() ? subRowInstance.description : subRowInstance.entity;
            }
            if (!string.IsNullOrEmpty(p.CM))
            {
                string fieldValue = p.CM;
                fieldValue = string.IsNullOrEmpty(fieldValue) ? "0" : fieldValue;

                if (fieldValue.IndexOf('.') != -1)
                {
                    string left = decimal.Parse(fieldValue.Split('.')[0]).ToString("N0");
                    fieldValue = left + "." + fieldValue.Split('.')[1];
                }
                else
                    fieldValue = decimal.Parse(fieldValue).ToString("N0");

                var monthPro = ins.GetType().GetProperty("Month" + month);
                monthPro.SetValue(ins, fieldValue, null);
            }

            if (!fieldExist)
            {
                if (p.bold)
                    ins.Description = string.Format("<strong>{0}</strong>", ins.Description);

                if (insert)
                    TableData.Insert(index, ins);
                else
                    TableData.Add(ins);
            }

            return ins;
        }

        private bool StartWithProfix(string a)
        {
            //foreach (var item in Relationships.Profix)
            //{
            //    if (a.StartsWith(item))
            //        return true;
            //}
            return false;
        }
    }
}
